<template>
  <a-layout>
    <a-layout-header class="header" :style="{ position: 'fixed', zIndex: 2, width: '100%' }">
      <div class="header">
        <div class="header-title">
          <div class="logo">
          </div>
          <div class="header-router">
            <div class="router-ul">
              <div class="router-li"
                   v-for="item in headerRouter"
                   :key="item.key"
                   :class="{'row': true, 'active': row(item)}"
                   @click="(e) => handleClick(e, item)"
              >
                {{item.title}}
              </div>
            </div>
          </div>
        </div>
        <div class="avatar">
          <div class="avatar-tool">
            <MessageOutlined  :style="{marginRight: '10px', fontSize: '16px', color: '#0062AD'}"/>
            <a-badge count="5" :offset="[5, -5]">
              <span> 消息</span>
            </a-badge>
          </div>
          <div class="avatar-tool">
            <ToolOutlined :style="{fontSize: '16px', color: '#0062AD'}"/>
            <a-dropdown>
              <a class="ant-dropdown-link" @click.prevent>
                快捷工具
                <DownOutlined />
              </a>
              <template #overlay>
                <a-menu>
                  <a-menu-item>
                    <a href="javascript:;">运费计算</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;">容量转换</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;">币种换算</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;">碳排放统计</a>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </div>
          <a-divider type="vertical" :style="{ height:'16px',marginTop:' 24px',marginRight: '30px'}" />
          <a-dropdown placement="bottomLeft">
            <div class="user">
              <a-avatar>
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <span class="name">{{user.name || ''}}</span>
              <DownOutlined />
            </div>
            <template #overlay>
              <a-menu>
                <a-menu-item >资料设置</a-menu-item>
                <a-menu-item >修改密码</a-menu-item>
                <a-menu-item @click="logout">退出登录</a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </a-layout-header>
    <a-layout-sider id="layout-menu" width="200"
                    :style="{borderRight: '1px solid #DCDEE0', overflow: 'auto', height: '100vh', position: 'fixed', left: 0, top: '64px', bottom: 0, background: '#fff' }"
                    v-model:collapsed="collapsed" collapsed>
      <a-menu
          v-model:selectedKeys="selectedKeys"
          :openKeys="openKeys"
          :style="{background: '#fff', height: '60%', overflowY: 'scroll', overflowX: 'hidden'}"
          style="background: #fff"
          @click="handleClickMenu"
          mode="inline">
        <template v-for="item in menu.list" >
          <a-menu-item :to="item.path" v-if="!item.children.length" v-bind:key="item.path">
            <template #icon>
            <span>
               <component :is="$icons[item.icon]"/>
            </span>
            </template>
            <router-link :to="item.path">
              {{item.title}}
            </router-link>
          </a-menu-item>
          <a-sub-menu v-else v-bind:key="item.key">
            <template #title>
            <span>
               <component :is="$icons[item.icon]"/>
              <span>{{item.title}}</span>
            </span>
            </template>
            <a-menu-item  v-for="menuChildren in item.children" v-bind:key="menuChildren.path">
              <router-link :to="menuChildren.path">
                {{menuChildren.title}}
              </router-link>
            </a-menu-item>
          </a-sub-menu>
        </template>
      </a-menu>
      <div :class="{
         'trigger-box' : true,
        'change-trigger': collapsed
       }" @click="collapsedClick">
        <MenuUnfoldOutlined :style="{marginRight: '10px'}"/>
        <span v-if="collapsed">展开</span>
        <span v-else>收起</span>
        <img src="@/assets/images/chunbo.jpg" alt="">
      </div>
    </a-layout-sider>
      <a-layout-content
          :style="{ background: '#F7F8FA', padding: '24px', marginTop: '64px', minHeight: 'auto', marginLeft: !collapsed? '200px': '80px'}"
      >
        <div class="bread-scroll">
<!--          <div class="breadcrumb-btn" @click="transLeft">-->
<!--            <LeftOutlined />-->
<!--          </div>-->
          <div  ref="scrollWrapper">
            <div class="breadcrumb-box">
              <div class="bread-item" v-for="(item,index) of breadcrumbList.data" :key="index">
                <div
                    ref="breadLists"
                    :style="{transform: `translateX(-${navOffset})px`, transition: 'transform .3s'}"
                    :class="{'bread-txt': true,
            'bread-text-four': item.meta.title && item.meta.title.length === 4,
             'bread-txt-active': item.path === route.path}">
                  <a-tooltip placement="topLeft"  overlayClassName="bgc_tooltip">
                    <template v-slot:title="title">
                      <span :style="{cursor: 'pointer'}" @click="openRouterLink(item)">新标签打开</span>
                    </template>
                    <router-link :to="{path: item.path, query: item.query}">{{item.meta.title}}</router-link>
                  </a-tooltip>
                  <CloseOutlined @click="closeRoute(item, index)" :style="{paddingLeft: '10px', marginTop: '3px', cursor: 'pointer'}"/>
                </div>
                <a-divider v-if="breadcrumbList.data.length - 1 !== index" type="vertical" :style="{marginTop: '10px', height: '20px'}"/>
              </div>
            </div>
          </div>
<!--          <div class="breadcrumb-btn" @click="transRight">-->
<!--            <RightOutlined/>-->
<!--          </div>-->
        </div>
        <router-view />
      </a-layout-content>
    </a-layout>
</template>

<script setup>
import  { reactive, ref, watch, onMounted, getCurrentInstance} from 'vue';
const { proxy  } = getCurrentInstance()
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';
const route = useRoute()
import { UserOutlined,CloseOutlined, DownOutlined,MessageOutlined, ToolOutlined, MenuUnfoldOutlined, RightOutlined, LeftOutlined } from '@ant-design/icons-vue';
const store = useStore();
const router = useRouter();
const activeKey = ref( '')  // 当前激活菜单
const collapsed = ref(false)
const selectedKeys = ref([route.path])
const openKeys = ref(['b1'])
const isDelete = ref(false)
const navOffset = ref(0)
const breadcrumbList = reactive({
  data: [route]
})
const deleteBread = ref([])

let headerRouter = [
  {
    title: '首页',
    key: 'a1',
    path: '/home'
  },
  {
    title: '工作台',
    key: 'a2',
    path: '/workbench'
  },
  {
    title: '数据看板',
    key: 'a3',
    path: '/home'
  },
  {
    title: '海图',
    key: 'a4',
    path: '/NauticalChart',
    meta: {
      title: '海图',
      isChild: false
    },
  }
]
let menu = reactive({     //菜单
  list: [
    {
      name: '合同执行',
      title: '合同执行',
      key: 'b1',
      path: '',
      icon: 'FileSearchOutlined',
      children: [
        {
          name: '资源合同',
          title: '资源合同',
          path: '/resourcecontract',
          key: 'b1-1',
          icon: '',
          children: false
        },
        {
          name: '船运合同',
          title: '船运合同',
          path: '/shippingContract',
          key: 'b1-5',
          icon: '',
          children: false
        },
        {
          name: '船舶代理合同',
          title: '船舶代理合同',
          path: '/ShipAgencyContract',
          key: 'b1-6',
          icon: '',
          children: false
        },
        {
          name: '第三方计量合同',
          title: '第三方计量合同',
          path: '/thirdMContract',
          key: 'b1-7',
          icon: '',
          children: false
        },
        {
          name: '保险合同',
          title: '保险合同',
          path: '/InsuranceContract',
          key: 'b1-8',
          icon: '',
          children: false
        },
        {
          name: '加油合同',
          title: '加油合同',
          path: '/RefuelingContract',
          key: 'b1-9',
          icon: '',
          children: false
        },
        {
          name: '律师合同',
          title: '律师合同',
          path: '/LawyersContract',
          key: 'b1-10',
          icon: '',
          children: false
        },
        {
          name: '合同范本',
          title: '合同范本',
          path: '/contractForm',
          key: 'b1-2',
          icon: '',
          children: []
        },
        // {
        //   name: 'PDF测试',
        //   title: 'PDF测试',
        //   path: '/PdfInfo',
        //   key: 'b1-3',
        //   icon: '',
        //   children: false
        // },
        {
          name: '合同标签',
          title: '合同标签',
          path: '/ContractLabel',
          key: 'b1-4',
          icon: '',
          children: false
        }
      ]
    },
    {
      name: '船舶调度',
      title: '船舶调度',
      key: 'b2',
      path: '',
      icon: 'NodeIndexOutlined',
      children: [
        {
          name: '船货排布',
          title: '船货排布',
          path: '/arrangement',
          key: 'b2-1',
          icon: '',
          children: false
        },
        {
          name: '年度计划',
          title: '年度计划',
          path: '/plan',
          key: 'b2-3',
          icon: '',
          children: false
        },
        {
          name: '调度优化',
          title: '调度优化',
          path: '/scheduling',
          key: 'b2-2',
          icon: '',
          children: false
        },
        {
          name: '可用船只',
          title: '可用船只',
          path: '/vessel',
          key: 'b2-4',
          icon: '',
          children: false
        }
      ]
    },
    {
      name: '船务执行',
      title: '船务执行',
      path: '',
      key: 'b4',
      icon: 'NodeExpandOutlined',
      children: [
        {
          name: '船运执行',
          title: '船运执行',
          path: '/ShipExecution',
          key: 'b4-1',
          icon: '',
          children: false
        },
      ]
    },
    {
      name: '系统管理',
      title: '系统管理',
      key: 'b3',
      path: '',
      icon: 'GatewayOutlined',
      children: [
        {
          name: '导出任务',
          title: '导出任务',
          path: '/exportList',
          key: 'b3-1',
          icon: '',
          children: false
        }
      ]
    }
  ]
});
console.log('router', router)
console.log('调换了route', route.query)
let breadArr = ref([{
  path: '/resourcecontract',
  meta: {
    title: '资源合同'
  }
}])
const allBreadInfo = ref([])
const breadcrumFn = () => {
  console.log('breadArr', breadArr.value)
  let localRouter = []
  if (sessionStorage.getItem('breadArr')) {
    localRouter = JSON.parse(sessionStorage.getItem('breadArr'))
  }
  if (route.meta.isChild) {
    let breadChildObj = {}
    Object.assign(breadChildObj, {
      path: route.path,
      meta: {
        title: route.meta.title
      },
      query: route.query
    })
    breadArr.value.push(breadChildObj)
  } else {
    let breadChildObj = {}
    Object.assign(breadChildObj, {
      path: route.path,
      meta: {
        title: route.meta.title
      }
    })
    breadArr.value.push(breadChildObj)
  }
  let lastArr = breadArr.value.concat(localRouter)
  allBreadInfo.value = lastArr
  const hash = {}
  const newArr = lastArr.reduce((item,next) => {
    hash[next.path]? '' : hash[next.path] = true && item.push(next)
    return item
  }, [])
  console.log('原来的数据', lastArr)
  console.log('最后的而数据66', deleteBread.value)
  if (deleteBread.value &&  deleteBread.value.length > 0) {
       deleteBread.value.map(dItem => {
         newArr.map((nItem,index) => {
         if (nItem.path === dItem.path) {
           newArr.splice(index, 1)
         }
       })
     })
    console.log('最后的而数据', newArr)
    return newArr
  } else {
    return newArr
  }
}
const closeRoute = (item1, index) => {
  breadcrumbList.data = breadcrumbList.data.filter((item) => item.path !== item1.path)
  deleteBread.value.push(item1)
  console.log(' deleteBread.value',  deleteBread.value)
  // sessionStorage.setItem('breadArr', JSON.stringify(deleteBread.value))
  console.log('route', item1)
  console.log('breadcrumbList.data', breadcrumbList.data)
  if (breadcrumbList.data.length === 0) {
    router.push('/')
  } else {
    if (index === 0) {
      if (breadcrumbList.data[index].query) {
        router.push({
          path: breadcrumbList.data[index].path,
          query: {
            id: breadcrumbList.data[index].query.id,
            tab: breadcrumbList.data[index].query.tab
          }
        })
      } else {
        router.push({
          path: breadcrumbList.data[index].path
        })
      }
    } else {
      if (breadcrumbList.data[index-1].query) {
        router.push({
          path: breadcrumbList.data[index - 1].path,
          query: {
            id: breadcrumbList.data[index - 1].query.id,
            tab: breadcrumbList.data[index - 1].query.tab
          }
        })
      } else {
        router.push({
          path: breadcrumbList.data[index - 1].path,
        })
      }

    }
  }

}
/**
 * 另外打开页面
 * */
const openRouterLink = (item) => {
  console.log(item)
  let infoObj = {}
  allBreadInfo.value.map(infoItem => {
    if (infoItem.path === item.path) {
      infoObj = infoItem
    }
  })
  let routeUrl = ''
  if (item.query) {
    routeUrl = router.resolve({
      path: item.path,
      query: {
        id:infoObj.query.id,
        tab: infoObj.query.tab
      }
    });
  } else {
    routeUrl = router.resolve({
      path: item.path
    });
  }
  window.open(routeUrl.href, '_blank');
}
const user = {
  name: localStorage.getItem('userName')
}
// 退出登录
const logout = () => {
 // store.commit('user/setToken', '')
  localStorage.removeItem('token')
  localStorage.removeItem('userName')
  router.push('/login')
};
// 通过权限，监控路由
router.beforeEach((to, from, next) => {
  // let flag = permission.value.some(item => item.path === to.path);
  let flag = true
  if(flag) {
    next();
  } else {
    router.push('/login')
  }
});
// 菜单激活状态
const scrollWrapper = ref(null)
const row = (d) => {
  return activeKey.value === d.key
};
const selecKeyClick = () => {
  let selectKeyArr = []
  if (route.meta.isChild){
    selectKeyArr.push(route.meta.parentPath)
  } else {
    selectKeyArr.push(route.path)
  }
  return selectKeyArr
}
const handleClickMenu = (e) => {
  console.log('点击了菜单', e)
  activeKey.value = ''
  deleteBread.value.map((item, index) => {
    if (item.path === route.path) {
      deleteBread.value.splice(index, 1)
    }
  })
  scrollWrapper.value.style.display = 'block'
  console.log('新增了那个路由', route)
  // router.push(e.item.to)
  // selectedKeys.value.push(e.key)
}
const handleClick = (e, d) => {
  if (scrollWrapper.value) {
    scrollWrapper.value.style.display = 'none'
  }
  e.stopPropagation();
  activeKey.value = d.key
  selectedKeys.value = []
  console.log('路由头部', d);
  router.push(d.path)
}
const breadLists = ref()
const transRight = () => {
  console.log('滑动e')
  const containerSize = scrollWrapper.value.offsetWidth
  const navSize = breadLists.value.offsetWidth
  navOffset.value = Math.min(navOffset.value + containerSize / 2, navSize - containerSize)
  console.log('滑动', containerSize)
  console.log('滑动navSize', navSize)
  console.log('滑动navSize', breadLists.value)
  console.log('滑动navOffset', navOffset.value)
  console.log('滑动navOffset', navOffset.value + containerSize / 2)
}
const transLeft = () => {
  console.log('滑动e')
  const containerSize = scrollWrapper.value.offsetWidth
  navOffset.value = Math.max(0, navOffset.value-containerSize/2)
  console.log('滑动', containerSize)
  console.log('滑动navOffset', navOffset.value)
  console.log('滑动navOffset', navOffset.value-containerSize/2)
}
watch(() => route, (newval) => {
  console.log('现在是那个路由', openKeys)
  openKeys.value = []
  openKeys.value.push(newval.meta.parentKey)
  let headRouterPath = []
  headerRouter.map(item => {
    headRouterPath.push(item.path)
  })
  if (!headRouterPath.includes(newval.path)) {
    if (newval) {
      deleteBread.value.map((item, index) => {
        if (item.path === newval.path) {
          deleteBread.value.splice(index, 1)
        }
      })
    }
    breadcrumbList.data = breadcrumFn()
    selectedKeys.value = selecKeyClick()
    console.log('新增了那个路由A', breadcrumbList.data)
    sessionStorage.setItem('breadArr', JSON.stringify(breadcrumbList.data))
    sessionStorage.setItem('selectkeyArr', JSON.stringify(selectedKeys.value))
    console.log('路由变化没3', newval)
  }

}, {deep: true});
watch( () => deleteBread.value, (newVal) => {
  deleteBread.value = newVal
})
const collapsedClick = () => {
  collapsed.value = !collapsed.value
}
onMounted(() => {
  breadcrumbList.data = breadcrumFn()
  selectedKeys.value = selecKeyClick()
  sessionStorage.setItem('breadArr', JSON.stringify(breadcrumbList.data))
  sessionStorage.setItem('selectkeyArr', JSON.stringify(selectedKeys.value))
  if (sessionStorage.getItem('breadArr')) {
    const localRouter = JSON.parse(sessionStorage.getItem('breadArr'))
    const selectRouter = JSON.parse(sessionStorage.getItem('selectkeyArr'))
    if (localRouter && localRouter.length > 0) {
      breadcrumbList.data = localRouter
    } else if (selectRouter && selectRouter.length > 0) {
      selectedKeys.value = selectRouter
    }
    scrollWrapper.value.style.display = 'block'
  }
  console.log('拿到的数据',  breadcrumbList.data)
})
</script>

<style lang="scss" scoped>
.header {
  width: 100%;
  height: 64px;
  position: relative;
  box-shadow:  0 1px 4px rgba(0,21,41,.08);
  display: flex;
  .avatar {
    display: flex;
    position: absolute;
    right: 10px;
    line-height: 64px;
    cursor: pointer;
    font-size: 14px;
    padding-right: 24px;
    .name {
      padding: 0 10px;
    }
    .avatar-tool {
      width: 150px;
      text-align: center;
    }
  }
  .header-title {
    display: flex;
    .header-img {
      width: 250px;
      font-size: 30px;
      line-height: 50px;
    }
    .logo {
     // float: left;
      width: 250px;
      height: 52px;
      margin: 5px 24px 5px 20px;
      //background: rgba(84, 8, 8, 0.3);
      //background: url("../../assets/images/logo.jpg") no-repeat;
      background-size: contain;
    }
    .header-router {
      .router-ul {
        display: flex;
        .router-li {
          width: 150px;
          height: 36px;
          line-height: 36px;
          font-size: 14px;
          text-align: center;
          margin-top: 15px;
          &:hover {
            cursor: pointer;
          }
        }
        .row.active {
          cursor: pointer;
          color: #0062AD;
          background-color: rgba(236, 242, 254, 1);
        }
      }
    }
  }
}
.trigger-box {
  cursor: pointer;
  font-size: 16px;
  width: 200px;
  text-align: center;
  margin-top: 50px;
  position: fixed;
  bottom: 0;
  img {
    margin-top: 20px;
    width: 200px;
    height: 125px;
  }
}
.change-trigger {
  cursor: pointer;
  font-size: 16px;
  width: 80px;
  text-align: center;
  img {
    display: none;
  }
}
.breadcrumb-box {
  text-align: left;
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  //width: 99%;
  //overflow: hidden;
  .bread-item {
    font-size: 14px;
    color: #6B7A8B;
    height: 32px;
    display: flex;
    margin-bottom: 15px;
    .bread-txt {
      //width: 150px;
      display: flex;
      justify-content: space-between;
      padding: 6px 16px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      color: #6B7A8B;
      &:hover {
        background-color: rgba(0, 98, 173, 0.05);
        color:#0062AD;
        border-radius: 2px;
        font-weight: 500;
      }
    }
    .bread-text-four{
      //width: 150px;
    }
    .bread-txt-active {
      //width: 100%;
      background-color: rgba(0, 98, 173, 0.05);
      color:#0062AD;
      border-radius: 2px;
      a{
        color:#0062AD;
      }
    }
  }
}
.bread-scroll {
  display: flex;
}
.breadcrumb-btn {
  font-size: 20px;
  margin-right: 10px;
  cursor: pointer;
}
</style>
